import logo from "@/assets/logo.png"
import { Form, Input, Checkbox, Button, message } from "antd"
import { UserOutlined, LockOutlined } from "@ant-design/icons"
import { useDispatch } from "react-redux"
import { loginAction } from "@/store/actions/user"
import { useHistory } from "react-router-dom"
import "./index.scss"

const loginRules = [
  {
    required: true,
    message: "手机号不能为空",
  },
  {
    pattern: /^1[3-9]\d{9}$/,
    message: "手机号格式不正确",
  },
]
const codeRules = [
  {
    required: true,
    message: "验证码不能为空",
  },
  {
    pattern: /^\d{6}$/,
    message: "验证码格式不正确",
  },
]
const isAgreeRules = [
  {
    validator(rule, value) {
      return value
        ? Promise.resolve()
        : Promise.reject(new Error("您还勾选同意用户协议和隐私条款"))
    },
  },
]

const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const onFinish = async (values) => {
    // values就是表单的内容
    // 派发异步的action  thunkaction
    await dispatch(loginAction(values)) // 派发action
    message.success("登录成功")
    // 走到这个位置说明登录成功
    console.log(history.location.state)
    history.replace(history.location?.state?.from || "/home") // 跳转到主页
  }

  return (
    <div className="login">
      <div className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        {/* validateTrigger=["onBlur", "onChange"] "onBlur" */}
        <Form
          initialValues={{
            mobile: "13911111111",
            code: "246810",
            isAgree: true,
          }}
          onFinish={onFinish}
          size="large"
          validateTrigger="onBlur"
        >
          <Form.Item name="mobile" rules={loginRules}>
            <Input prefix={<UserOutlined />} placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item name="code" rules={codeRules}>
            <Input prefix={<LockOutlined />} placeholder="请输入验证码" />
          </Form.Item>
          <Form.Item
            name="isAgree"
            rules={isAgreeRules}
            valuePropName="checked"
          >
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" block htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
